import {
  defineComponent,
  h,
  PropType,
  reactive,
  resolveComponent,
  VNode,
} from 'vue';
import { useController, useNamespace } from '@ibiz-template/vue3-util';
import { calcDeCodeNameById, EventBase } from '@ibiz-template/runtime';
import { FormMDCtrlFormController } from './form-mdctrl-form.controller';
import FormMDCtrlContainer from '../form-mdctrl-container/form-mdctrl-container';

export const FormMDCtrlForm = defineComponent({
  name: 'IBizFormMDCtrlForm',
  props: {
    controller: {
      type: Object as PropType<FormMDCtrlFormController>,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-mdctrl');

    useController(props.controller);

    const c = props.controller;
    c.state = reactive(c.state);
    return { ns, c };
  },
  render() {
    const c = this.c;
    const renderContent = (): VNode[] | undefined => {
      if (c.controlModel && c.provider) {
        return c.state.data.map((item: IData, index: number) => {
          const tempContext = c.parent.form.context.clone();
          if (c.model.contentControl) {
            const codeName = calcDeCodeNameById(
              c.model.contentControl.appDataEntityId!,
            );
            tempContext[codeName] = item.srfkey;
          }
          const controlProps = {
            modelData: c.controlModel,
            context: tempContext,
            params: c.parent.form.params,
            onFormDataChange: (arg: EventBase): void =>
              c.onFormChange(arg.data, index),
            onRemoveSuccess: (): void => c.onFormRemoveSuccess(index),
            onMounted: (event: EventBase): void =>
              c.onControlMounted(event, index),
          };
          const controlComponent = h(
            resolveComponent(c.provider.component),
            controlProps,
          );
          return (
            <div class={this.ns.b('form-content')} key={item.srfkey}>
              {controlComponent}
              <div class={this.ns.b('btn')}>
                <el-button
                  type='danger'
                  class={this.ns.b('remove-btn')}
                  onClick={(): void => this.c.onDataRemove(index)}
                >
                  删除
                </el-button>
              </div>
            </div>
          );
        });
      }
    };
    return (
      <FormMDCtrlContainer
        controller={c.parent}
        onInsertButtonClick={(): void => {
          c.onDataInsert();
        }}
      >
        {renderContent()}
      </FormMDCtrlContainer>
    );
  },
});

export default FormMDCtrlForm;
